<template>
    <div class="cartContainer">
        <el-table
            :data="cartList"
            v-loading="isLoading"
            @selection-change="selectionChange"
            @select-all="selectAll"
            ref="table"
        >
            <template #empty>
                <div class="empty">
                    <span>购物车空空的，快去添加商品吧</span>
                    <el-button type="primary" @click="$router.replace({ name: 'home' })">回到首页</el-button>
                </div>
            </template>
            <el-table-column type="selection" width="60" />
            <el-table-column type="index" label="序号" width="60" />
            <el-table-column prop="coverImg" label="图片">
                <template #default="scope">
                    <el-image :src="scope.row.coverImg" style="width: 80px"></el-image>
                </template>
            </el-table-column>
            <el-table-column prop="title" label="书名"></el-table-column>
            <el-table-column prop="author" label="作者"></el-table-column>
            <el-table-column label="单价">
                <template #default="scope">
                    <span>{{ scope.row.price.toFixed(2) }}元</span>
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template #default="scope">
                    <el-button type="text" @click="currentDelete(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <div class="footer">
            <div class="left">
                <el-checkbox
                    :label="toggleAllChecked ? '取消全选' : '全选'"
                    @change="selectAllChecked"
                    v-model="toggleAllChecked"
                ></el-checkbox>
                <el-button type="danger" :disabled="selectedCount === 0" @click="deleteSelected">删除</el-button>
            </div>
            <div class="right">
                <span style="margin-right: 1rem"
                    >已选商品：<span style="font-size: 1.4rem">{{ selectedCount }}</span> 件</span
                >
                <span style="margin-right: 1rem"
                    >合计（不含运费）：<span style="color: orange; font-size: 1.4rem">￥{{ totalPrice }}</span></span
                >
                <el-button type="primary" :disabled="selectedCount === 0" @click="settleHandler">结算</el-button>
            </div>
        </div>
    </div>
</template>

<script>
import store from "@/store";
import service from "@/utils/request";
import { ElMessage } from "element-plus";

export default {
    name: "CartView",
    data() {
        return {
            cartList: [],
            selectedCount: 0,
            totalPrice: "0.00",
            isLoading: true,
            toggleAllChecked: false,
            currentPage: 1,
            pageSize: 5,
        };
    },
    methods: {
        // 多选事件
        selectionChange(values) {
            // console.log(this.toggleAllChecked);
            let price = 0;
            this.selectedCount = values.length;
            values.forEach((item) => {
                price += item.price;
            });
            this.totalPrice = price.toFixed(2).toString();
        },
        // 全选框事件
        selectAllChecked() {
            this.$refs["table"].toggleAllSelection();
        },
        // 删除当前行
        currentDelete(row) {
            // console.log(row.orderID);
            service({
                method: "get",
                url: `/order/delete?id=${row.orderID}`,
                headers: {
                    token: store.state.token,
                },
            }).then(() => {
                ElMessage({
                    type: "success",
                    message: "删除成功",
                });
                this.refresh();
            });
        },
        // 删除选中行
        deleteSelected() {
            let rows = this.$refs["table"].getSelectionRows();
            rows.forEach((item) => {
                service({
                    method: "get",
                    url: `/order/delete?id=${item.orderID}`,
                    headers: {
                        token: store.state.token,
                    },
                }).then(() => {
                    this.refresh();
                });
            });
            ElMessage({
                type: "success",
                message: "删除成功",
            });
        },
        // 结算事件
        settleHandler() {
            let rows = this.$refs["table"].getSelectionRows();
            rows.forEach((item) => {
                service.post(`/order/update`, { ...item, orderState: 2 }).then((res) => {
                    // console.log(res);
                    this.$router.replace({ name: "settle" });
                });
            });
        },
        refresh() {
            let userID = store.state.userInfo.userID;
            service({
                method: "get",
                url: `/order/selectById/${userID}?orderState=1`,
                headers: {
                    token: store.state.token,
                },
            }).then((res) => {
                console.log(res.data);
                res.data.forEach((item) => {
                    Object.assign(item, ...item.book, item);
                    delete item["book"];
                    // console.log(item);
                });
                this.cartList = res.data;
                // console.log(this.cartList);
            });
        },
    },
    watch: {
        // 监听选中数量并更改全选框状态
        selectedCount(oldVal) {
            if (oldVal === this.cartList.length) {
                this.toggleAllChecked = true;
            } else {
                this.toggleAllChecked = false;
            }
            // console.log(this.toggleAllChecked);
        },
    },
    async beforeMount() {
        // orderState=1时为待付款状态
        this.isLoading = true;
        await this.refresh();
        this.isLoading = false;
    },
};
</script>

<style lang="scss" scoped>
.cartContainer {
    width: 100%;
    display: flex;

    .el-table {
        width: 100%;

        .empty {
            display: flex;
            flex-direction: column;
            margin-bottom: 1rem;
            justify-content: center;
            align-items: center;

            .el-button {
                width: 6rem;
            }
        }
    }

    .footer {
        width: 97%;
        padding: 0 20px;
        height: 60px;
        bottom: 0;
        position: fixed;
        border-top: 1px solid #ccc;
        z-index: 999;
        backdrop-filter: blur(10px);
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        align-items: center;

        .left {
            display: flex;
            align-items: center;

            .el-checkbox {
                margin-right: 1rem;
            }
        }

        .right {
            height: 60px;
            display: flex;
            flex-direction: row;
            justify-content: center;
            align-items: center;
        }
    }
}
</style>
